﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class VBOUtil : MonoBehaviour
{

    private static List<Vector3> list = new List<Vector3>();

    public static bool PolygonIsContainPoint(Vector3 point, Vector3[] vertexs)
    {
        list.Clear();

        for (int i = 0; i < vertexs.Length; ++i)
            list.Add(vertexs[i]);

        return PolygonIsContainPoint(point, list);
    }

    /// <summary>
    /// |Ax*Th/2| + |Ay*Tw/2|=Th*Tw/4 时点是在菱形上的。>时在菱形区域外，<时在菱形内的。
    //其中Ax代表点的X坐标，Ay代表点的Y坐标，Tw代表菱形的宽度，Th代表菱形的高度。
    //进一步优化得到|Ax* Th| + |Ay* Tw|<Th* Tw*0.5
    /// </summary>
    /// <param name="point"></param>
    /// <param name="vertexs"></param>
    /// <returns></returns>
    public static bool PolygonIsContainPoint(Vector3 point, List<Vector3> vertexs)
    {
        vertexs.Add(vertexs[0]);

        int count = 0;

        for (int i = 0; i < vertexs.Count - 1; ++i)
        {
            if (!isLeft(point, vertexs[i + 1], vertexs[i]))
                count++;
        }

        if (count == 4)
        {
            return true;
        }

        return false;
    }

    static bool isLeft(Vector3 P0, Vector3 P1, Vector3 P2)
    {

        int abc = (int)((P1.x - P0.x) * (P2.y - P0.y) - (P2.x - P0.x) * (P1.y - P0.y));

        return (abc < 0) ? true : false;
    }
}
